package sg.edu.nus.comp.cs4218.impl.fileutils;

import java.io.File;

import sg.edu.nus.comp.cs4218.fileutils.ICdTool;
import sg.edu.nus.comp.cs4218.impl.ATool;
import sg.edu.nus.comp.cs4218.impl.Shell;

public class CdTool extends ATool implements ICdTool {
	private String message;
	private File currentDir;

	/**
	 * Constructor
	 * 
	 * @param arguments
	 *            - Arguments the tool is going to be executed with.
	 */
	public CdTool(String[] arguments) {
		super(arguments);
		setStatusCode(0);
	}

	/**
	 * Changes current working directory to the specified directory
	 * 
	 * @param newDirectory
	 *            - The specified directory
	 * @return File representation of the new working directory
	 */
	@Override
	public File changeDirectory(String newDirectory) {
		File newDir = null;
		if (newDirectory.equals("..")) {
			newDir = currentDir.getParentFile();
		} else {
			newDir = Shell.getFile(currentDir, newDirectory);
		}
		if (newDir == null || !newDir.exists() || !newDir.isDirectory()) {
			setStatusCode(1);
			message = "Unable to find specified directory";
		}
		Shell.workingDir = newDir;
		return newDir;
	}

	/**
	 * Changes current working directory
	 * 
	 * @param stdin
	 *            - Input on stdin. NOT THE ARGUMENTS! Can be null.
	 * @return Output on stdout
	 */
	@Override
	public String execute(File workingDir, String stdin) {
		currentDir = workingDir;

		if (super.args == null) {		
			setStatusCode(1);
			message = "Invalid change directory command";
		} 

		if (getStatusCode() == 0) {
			if (super.args.length >= 1) {
				if (super.args[0].equals("-") == false) {
					File newDirectory = changeDirectory(super.args[0]);
					if (getStatusCode() == 0) {
						message = newDirectory.getAbsolutePath();
					}
				}
				else {
					if (stdin != null) {
						File newDirectory = changeDirectory(stdin);
						if (getStatusCode() == 0) {
							message = newDirectory.getAbsolutePath();
						}
					}
					else {
						setStatusCode(1);
						message = "Invalid change directory command";
					}
				}
			} else {
				setStatusCode(1);
				message = "Invalid change directory command";
			}
		}
		return message;
	}
}
